import React, { useEffect, useState, useContext } from 'react';
import { useDispatch, useSelector } from 'dva';
import { Form, Input, Button } from 'antd';
import { Icon } from 'react-fa';
import Grid from '@/components/Grid';
import Layout from '@/components/Layout';
import Dialog from '@/components/Dialog';
import settings, { getPagination } from '@/settings';
import { createAction } from '@/utils';
import GroupContext from './groupContext';
import api from '@/api';

const ModelRoleList = props => {
  const dispatch = useDispatch()

  const [selectedRows, setSelectedRows] = useState([])

  const { 
    params = {},
    list = {}
  } = useSelector(_ => _.$role)

  const { data, total } = list

  const { effects } = useSelector(_ => _.loading)
  const loading = effects['$role/fetchList']

  useEffect(() => {
    dispatch(createAction('$role/fetchList')());
  }, [dispatch]);

  const handleSubmit = (_, callback) => {
    const ids = selectedRows.map(_ => _.id)
    // const _data = data.filter(_ => {
    //   return ids.indexOf(_.id) > -1
    // })
    callback({
      roleId: ids
    });
  };

  props.register(handleSubmit)

  const columns = [
    {
      title: '角色名称',
      dataIndex: 'name',
      width: 200,
    },
    {
      title: '描述',
      dataIndex: 'title',
      width: 200
    },
    {
      title: '备注',
      dataIndex: 'desc',
      width: 300
    },
  ];
  const handleSelectRows = rows => {
    setSelectedRows(rows)
  };
  const handleSearch = (value, e) => {
    e.preventDefault();
    const pagination = getPagination({
      pageNumber: 1,
    });
    dispatch(createAction('$role/fetchList')({
      ...params,
      ...pagination,
      [settings.search]: value,
    }));
  };
  const handleGridChange = (oldPagination, sorter) => {
    const pagination = getPagination(oldPagination);
    const payload = {
      ...params,
      ...pagination,
    };

    if (sorter.field) {
      payload.sorter = sorter.field;
      payload.order = sorter.order;
    }

    dispatch(createAction('$role/fetchList')(payload));
  };
  const handleReload = () => {
    dispatch(createAction('$role/fetchList')(params));
  };

  const pageNumber = params[settings.pageNumber];

  return (
    <Layout
      toolbar={
        <Form layout="inline">
          <Input.Search placeholder="请输入角色名称" onSearch={handleSearch} />
        </Form>
      }
    >
      <Grid
        selectedRows={selectedRows}
        onSelectRow={handleSelectRows}
        columns={columns}
        data={data}
        loading={loading}
        pagination={{
          pageNumber,
          total,
        }}
        onReload={handleReload}
        onChange={handleGridChange}
      />
    </Layout>
  );
}

const RolePage = props => {
  const dispatch = useDispatch()
  const [searchValue, setSearchValue] = useState("")
  const [selectedRows, setSelectedRows] = useState([])
  const { list = {}, params = {} } = useSelector(_ => _.group$role)
  const { data, total } = list
  const { effects } = useSelector(_ => _.loading)
  const loading = effects['group$role/fetchList']

  // const { groupId } = props
  const { groupId } = useContext(GroupContext)

  const columns = [
    {
      title: '角色名称',
      dataIndex: 'name',
      width: 200,
    },
    {
      title: '描述',
      dataIndex: 'title',
      width: 200
    },
    {
      title: '备注',
      dataIndex: 'desc',
      width: 300
    },
    {
      title: '操作',
      dataIndex: 'id',
      width: 200,
      align: 'center',
      render: (v, record, index) => {
        return (
          <span
            className="btn-text">
            <Icon
              name="edit"
              title="编辑"
            />
          </span>
        )
      }
    },
  ];
  useEffect(() => {
    setSearchValue("")
    setSelectedRows([])
    dispatch(createAction('group$role/fetchList')({
      id: groupId
    }));
  }, [dispatch, groupId]);
  const handleSelectRows = rows => {
    setSelectedRows(rows);
  };
  const handleAdd = () => {
    Dialog.drawer({
      title: '选择角色',
      width: 720,
      fixed: true,
      effect: true,
      data: {
        groupId
      },
      component: ModelRoleList,
      url: api.group_role_add,
      onOk: (data) => {
        handleReload();
      }
    });
  }
  const handleRemove = e => {
    Dialog.confirm({
      title: '确认提示',
      content: '确定要删除已选择的角色？',
      onOk: async () => {
        await dispatch(createAction('role/delete')({
          id: selectedRows.map(_ => _.id)
        }))
        handleReload();
      },
    });
  };
  const handleGridChange = (oldPagination, sorter) => {
    const pagination = getPagination(oldPagination);
    const payload = {
      ...params,
      ...pagination,
      id: groupId
    };

    if (sorter.field) {
      payload.sorter = sorter.field;
      payload.order = sorter.order;
    }

    dispatch(createAction('group$role/fetchList')(payload));
  };
  const handleReload = () => {
    dispatch(createAction('group$role/fetchList')({
      ...params,
      id: groupId
    }));
  };
  const handleSearchChange = ({ target: { value }}) => {
    setSearchValue(value)
  };
  const handleSearch = (value, e) => {
    e.preventDefault();
    const pagination = getPagination({
      pageNumber: 1,
    });
    dispatch(createAction('group$role/fetchList')({
      ...params,
      ...pagination,
      [settings.search]: value,
      id: groupId
    }));
  };

  const pageNumber = params[settings.pageNumber];

  return (
    <Layout
      toolbar={{
        left: (
          <React.Fragment>
            <Button type="primary" onClick={handleAdd}>
              导入
            </Button>
            <Button
              type="danger"
              disabled={selectedRows.length === 0}
              onClick={handleRemove}
            >
              删除
            </Button>
          </React.Fragment>
        ),
        right: (
          <Form layout="inline">
            <Input.Search placeholder="请输入角色名称或描述" value={searchValue} onChange={handleSearchChange} onSearch={handleSearch} />
          </Form>
        ),
      }}
    >
      <Grid
        selectedRows={selectedRows}
        onSelectRow={handleSelectRows}
        columns={columns}
        data={data}
        loading={loading}
        pagination={{
          pageNumber,
          total: total,
        }}
        onReload={handleReload}
        onChange={handleGridChange}
      />
    </Layout>
  );
}

// const RoleWrapPage = props => (
//   <GroupContext.Consumer>
//     {context => (
//       <RolePage {...props} groupId={context.groupId} />
//     )}
//   </GroupContext.Consumer>
// )

// export default RoleWrapPage;

export default RolePage